/* authentication related services */

var express = require('express')
var router = express.Router(),
    rp = require('request-promise'),
    debug = require('debug')('react-demo')

var configFile = 'config.'+process.env.NODE_ENV+'.json'
var config = require('../../config/'+configFile);
//var App = React.createFactory(main.App);

router.get("/", function(req, res, next){
  return res.json({
    data: ["abc", 'def', 'xyz']
  });
})

router.post("/login", function(req, res, next) {
  debug(req.body)
  var option = {
    method: 'POST',
    uri: config.apiHost+'/api/auth/login',
    body: req.body,
    json: true
  }

  rp(option)
  .then(function(response) {
    console.log(response)
    var data = response;

    if (data.success) {
      var access_token = data.access_token;
      res.cookie('access_token', access_token, {expires: new Date(Date.now() + 24 * 60 * 60 * 1 * 1000)})
      res.cookie('kerry_leave', new Date().getTime(), {expires: new Date(Date.now() + 24 * 60 * 60 * 1 * 1000)})
      // res.cookie('access_token', access_token)
      return res.json({
        success: true
      })
    }else {
      return res.status(403).json(data)
    }
  })
  .catch(function(err) {
    console.log(err)
    return res.status(err.statusCode).json({
                                 success: false
                                 ,errMsg: err.message
                                 ,errors: err
                                });
  })
})

router.get("/leave", function(req, res, next) {
  setTimeout(function() {
    debug("leave")
    res.clearCookie('access_token')
    return res.json({
      success: true
    })
  }, 2000)
})



module.exports = router;
